﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tyshka.Subroutines.Domain.Abstract;
using Tyshka.Subroutines.ViewModels;
using Tyshka.Subroutines.Filters;

namespace Tyshka.Subroutines.Controllers
{
    [AuthenticationFilter(false)]
    public class TagController : Controller
    {
        //
        // GET: /Tag/

        public ActionResult Index()
        {
            var tagRepository = (ITagRepository) DependencyResolver.Current.GetService(typeof (ITagRepository));
            var query = tagRepository.Query();

            var model = new TagListingModel {Items = new List<TagListingItem>()};
            foreach(var tag in query)
            {
                model.Items.Add(new TagListingItem
                                    {
                                        Name = tag.Name,
                                        SubroutinesCount = tag.SubroutineTags.Count,
                                        Id = tag.Id,
                                    }
                    );
            }

            return View("Index", model);
        }

        public ActionResult Detail(long id)
        {
            var tagRepository = (ITagRepository) DependencyResolver.Current.GetService(typeof (ITagRepository));
            var targetTag = tagRepository.Read(id);

            var subRepository = (ISubroutineRepository) DependencyResolver.Current.GetService(typeof (ISubroutineRepository));
            var query = subRepository.Query();

            if (targetTag == null)
            {
                return RedirectToAction("Error", "Error");
            }

            var model = new TagDetailModel
                            {
                                Items = new List<TagDetailModelItem>(),
                                Name = targetTag.Name,
                                SubroutinesLocalCount = targetTag.SubroutineTags.Count,
                                SubroutinesTotalCount = query.Count(),
                            };

            foreach (var subroutineTag in targetTag.SubroutineTags)
            {
                model.Items.Add(
                    new TagDetailModelItem
                        {
                            Author = subroutineTag.Subroutine.User.FullName,
                            Id = subroutineTag.SubroutineId,
                            Name = subroutineTag.Subroutine.Title,
                            Votes = subroutineTag.Subroutine.Votes,
                        }
                    );
            }

            return View("Detail", model);
        }

    }
}
